#include <platform.h>
#include <global.h>
#include <string>
#include <renderobject.h>
#include <applicationengine.h>

using namespace NITK;

static unsigned int randomColor()
{
    return Color::rgba(rand() % 256, rand() % 256, rand() % 256, rand() % 256);
}


enum { COUNT = 5 };
class Scene : public ApplicationEngine
{
public:
    Scene() : ApplicationEngine("Test", 1), draggedItem(0), timerId(-1)
    {
        enum { StringCount = 4 };
        static const char *names[StringCount] = { "foo", "bar", "barfood", "foodbar" };
        for (int i=0; i<COUNT; ++i) {
            renderObjects[i] = new RenderObject(RenderObject::Type_Normal, randomColor());
            if (i == 4)
                renderObjects[i]->setBackground("foo.jpg");
            renderObjects[i]->setForeground(randomColor());
            renderObjects[i]->setText(names[i % StringCount]);
            renderObjects[i]->setZValue(i);
            renderObjects[i]->setGeometry(Rectangle(i * 110, i * 110, 100, 100));
        }
        timerId = startTimer(100);
    }



    void timerEvent(int id)
    {
        static int counter = 20;
        if (!--counter) {
            Platform::instance()->stopTimer(id);
        }

        enum { NUM = (COUNT / 10) };
        for (int i=0; i<NUM; ++i) {
            const int index = rand() % COUNT;
            renderObjects[index]->setGeometry(Rectangle(rand() % 1000, rand() % 1000, (rand() % 100) + 10, (rand() % 100) + 10));
        }
    }

    virtual bool handlePress(const Point &pos)
    {
        if ((draggedItem = renderObjectAt(pos))) {
            stopTimer(timerId);
            timerId = -1;
            offset = pos - draggedItem->geometry().topLeft();
        }
        return true;
    }

    virtual bool handleDrag(const Point &pos)
    {
        if (draggedItem) {
            Rectangle r = draggedItem->geometry();
            r.topLeft() = pos - offset;
            draggedItem->setGeometry(r);
        }
        return true;
    }

    virtual bool handleRelease(const Point &)
    {
        if (timerId == -1)
            timerId = startTimer(100);
        draggedItem = 0;
        return true;
    }
private:
    RenderObject *renderObjects[COUNT];
    RenderObject *draggedItem;
    Point offset;
    int timerId;
};

int main(int argc, char **argv)
{
    srand(time(0));
    Platform p(argc, argv);
    Scene s;
    return p.exec();
}
